layui.use(['layer', 'element', 'laypage'], function () {
    var util = layui.util,
        carousel = layui.carousel,
        layer = layui.layer,
        element = layui.element,
        laypage = layui.laypage;
    element.init();
});

var page = 1; //设置首页页码
var limit = 27;  //设置一页显示的条数
var total;    //总条数
var isTopCount;//置顶页总条数
var postCount;//帖子条数
var indexUrl = "index/indexPage";
var topPageUrl = "index/topPage";

//请求数据
function loadData(url) {
    let $ = layui.jquery;
    myajax = $.post({
        url: url,//对应controller的URL
        data: {
            "page": page,
            "limit": limit
        },
        async: false,
        success: function (ret) {
            total = ret.count; //设置总条数
            isTopCount = url.startsWith("index/topPage") ? total : isTopCount;
            postCount = url.startsWith("index/indexPage") ? isTopCount : 0;
            let html = "";
            let data = ret.data;
            let dataList = url.startsWith("index/indexPage") ? $("#orderList") : $("#topList");
            dataList.empty(); //删除跳转页码前的数据
            for (var i = 0; i < data.length; i++) {
                html = staticHtml(data[i], i + postCount);
                dataList.append(html);
                isDisplay(data[i], i + postCount);
            }
        }
    });
}

//得到分页数据
function getPage(url) {
    layui.use('laypage', function () {
        var laypage = layui.laypage;
        //执行一个laypage实例
        laypage.render({
            elem: 'layPage' //注意，这里的 test1 是 ID，不用加 # 号
            , count: total, //数据总数，从服务端得到
            limit: limit,   //每页条数设置
            jump: function (obj, first) {
                //obj包含了当前分页的所有参数，比如：
                page = obj.curr;  //改变当前页码
                limit = obj.limit;
                //首次不执行
                if (!first) {
                    console.log(first);
                    loadData(url)  //加载数据
                }
            }
        });
    });
}

//动态判断页面元素是否显示
function isDisplay(value, index) {
    var isClosed = parseInt(value.isClosed);
    var isFine = value.isFine;
    var grade = parseInt(value.grade);
    if (isFine == 1) {
        document.getElementById("isFine" + index).innerHTML = "<span class=\"layui-badge layui-bg-red\">精贴</span>";
    }
    if (isClosed == 1) {
        document.getElementById("isClosed" + index).style.display = "inline-block";
    }
    var vip = grade < 200 ? 1 : (grade > 200 && grade <= 400 ? 2 : (grade > 400 && grade <= 800
        ? 3 : (grade > 800 && grade <= 1500 ? 4 : (grade > 1500 && grade <= 4000 ? 5 : (grade > 4000 && grade <= 8000
            ? 6 : (grade > 8000 && grade <= 15000 ? 7 : (grade > 15000 && grade <= 50000 ? 8 : (grade > 50000 ? 9 : 0))))))));
    if (vip != 0) {
        document.getElementById("grade" + index).style.display = "inline-block";
        document.getElementById("grade" + index).innerText = "VIP" + vip;
    }
}

//根据传入的数据返回html
function staticHtml(data, i) {
    return '<li><a href="javascript:gotoUserHomepage(' + data.userId + ');" class="fly-avatar"> <img\n' +
        '                src="upload/' + data.headImg + '" alt="出错了"> </a>\n' +
        '                    <h2><a class="layui-badge">' + data.columnName + '</a> <a\n' +
        '                href="javascript:gotoReplyPost(' + data.id + ');">' + data.title + '</a></h2>\n' +
        '                <div class="fly-list-info"><a href="javascript:gotoUserHomepage(' + data.userId + ');" link="">\n' +
        '                    <cite>' + data.nickName + '</cite><i id="grade' + i + '" class="layui-badge fly-badge-vip" style="display: none"></i></a>\n' +
        '                <span>' + data.createTime + '\n' +
        '                </span> <span class="fly-list-kiss layui-hide-xs" title="悬赏飞吻"><i\n' +
        '            class="iconfont icon-kiss"></i> ' + data.kiss + '</span>\n' +
        '                <span id="isClosed' + i + '" style="display: none" class="layui-badge fly-badge-accept layui-hide-xs">已结</span><span\n' +
        '            class="fly-list-nums"> <i class="iconfont icon-pinglun1"\n' +
        '                title="回答"></i> ' + data.replyNum + ' </span></div>\n' +
        '                <div id="isFine' + i + '" class="fly-list-badge"></div>\n' +
        '                </li>';
}

function toggleData(url, target) {
    page = 1;//重置页码
    $(".isCopy").show();
    $(".isHidden").hide();
    if (target.tagName == "LI" && $(target).children("a").eq(0).html() != "首页") {
        url += $(target).children("a").eq(0).html();
    } else if (target.tagName == "A") {
        $(".columnTitle li").each(function (i, e) {
            if ($(e).attr("class") == "layui-this" && $(target).html() != "综合") {
                url += "&columnName=" + $(e).children("a").eq(0).html();
            }
        });
    } else {
        $(".isCopy").hide();
        $(".isHidden").show();
    }
    loadData(url);
    getPage(url);
    change(target);
}

function loadToggleData(loc, index) {
    let columnName = decodeURI(loc.substring(index + 1), "utf-8");
    $(".columnTitle li").each(function (i, e) {
        if (e.children[0].innerHTML == columnName) {
            $(e).click();
        }
    });
}
//回帖周榜
function loadReplyList() {
    $.post('reply/replyList', function (ret) {
        let data = ret.data;
        let html = "";
        for (var i = 0; i < data.length; i++) {
            html += '<dd><a href="javascript:gotoUserHomepage('+data[i].userId+');"><img src="upload/' + data[i].headImg + '"><cite>' + data[i].nickName + '</cite><i>' + data[i].replyNum + '次回答</i></a></dd>';
        }
        $(".replyList").append(html);
    });
}
//本周热议
function loadHotPost() {
    $.post('index/hotPost', function (ret) {
        let data = ret.data;
        let html = "";
        for (var i = 0; i < data.length; i++) {
            html += '<dd><a href="javascript:gotoReplyPost('+data[i].id+');">' + data[i].title + '</a> <span><i\n' +
                'class="iconfont icon-pinglun1"></i>' + data[i].replyNum + '</span></dd>';
        }
        $(".hotPost").append(html);
    });
}

//回到首页
function gotoIndex() {
    location.href = "../index.jsp";
}

//回复页切换分类
function gotoIndexToggleData(target) {
    location.href = "../index.jsp?columnName=" + encodeURI(target.children[0].innerText);
}

//登入和注册
function gotoLoginAndRegister(type) {
    location.href = "../page/login-register.jsp";
}

//用户中心
function gotoUserCenter() {
    location.href = "../page/userCenter.jsp";
}

//基本设置
function gotoUserAset() {
    location.href = "../page/userAset.jsp";
}

//我的主页
function gotoUserHomepage(userId) {
    location.href = "../page/userHomepage.jsp?userId=" + userId;
}

//我的帖子
function gotoUserInvitation() {
    location.href = "../page/userInvitation.jsp";
}

//我的消息
function gotoUserMsg() {
    location.href = "../page/userMsg.jsp";
}

//发表新帖
function gotoSendPost(userId) {
    if (userId == null) {
        location.href = "../page/login-register.jsp";
        return;
    }
    location.href = "../page/sendPost.jsp";
}

//回帖
function gotoReplyPost(postId) {
    location.href = "../page/replyPost.jsp?postId=" + postId;
}

//用户退出
function logOut() {
    $.post('user/logOut', function (ret) {
        location.href = "../index.jsp";
    });
}

//今日是否签到
function isSign() {
    var userId = $(".signVal").val();
    layui.use(['jquery', 'form'], function () {
        let $ = layui.jquery,
            form = layui.form;
        if (userId != null && userId != "") {
            $.post('../sign/isSign', {'uId': userId}, function (ret) {
                let data = ret.data;
                if (ret.code == 0) {
                    if (ret.msg == "今日已签到") {
                        $("#LAY_signin").attr('disabled', 'disabled');
                        $("#LAY_signin").addClass("layui-btn-disabled").html(ret.msg);
                        $("#LAY_signin").next().html("已获得<cite>5</cite>飞吻");
                        $(".fly-signin-days").children('cite').html(data.signCount);
                        form.render();
                    }
                } else {
                    $("#LAY_signin").html(ret.msg);
                    $(".fly-signin-days").children('cite').html(data.signCount);
                }
            });
        }
    });
}

function gotoSign() {
    layui.use(['jquery', 'form'], function () {
        let $ = layui.jquery;
        var userId = $(".signVal").val();
        console.log(userId);
        if (userId == null || userId == "") {
            layer.msg("请先登入", {anim: 6});
            return;
        }
        $.post('../sign/doSign', {"uId": userId}, function (ret) {
            console.log(ret.msg);
            if (ret.code == 0) {
                gotoIndex();
            }
        });
    });
// <c:if test="${empty currentUser}">
//         layer.msg("请先登入", {anim: 6});
//     return;
// </c:if>
//     $.post('sign/doSign', {"uId": '${currentUser.id}'}, function (ret) {
//         console.log(ret.msg);
//         if (ret.code == 0) {
//             window.location.href = "../index.jsp";
//         }
//     });
}


